<!--创建考试安排-->
<template>
  <h4>创建考试安排</h4>
  <el-divider/>
  <el-button plain type="primary" @click="openDialog">创建考试安排</el-button>
  <el-divider/>
  <h4>所有考试安排</h4>
  <el-divider/>
  <edit />
  <el-dialog
      v-model="dialogVisible"
      title="创建新的考试"
      width="82%"
      :close-on-click-modal="false"
      @close="resetForm">
    <el-scrollbar height="650px">
      <!--  表单  -->
      <el-text type="primary">基本信息</el-text>
      <el-divider/>
      <el-form :model="examForm" :rules="formRules" ref="examFormRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="考试ID">
              <el-input v-model="examForm.id" disabled placeholder="自动生成"/>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="考试名称" prop="name">
              <el-input v-model="examForm.name" placeholder="请输入考试名称"/>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="创建时间">
              <el-input disabled :value="currentTime" placeholder="自动生成"/>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="教师ID">
              <el-input disabled :value="examForm.teacherId" placeholder="自动填充"/>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="教师姓名" prop="teacherName">
              <el-select
                  v-model="examForm.teacherName"
                  style="width: 100%"
                  placeholder="请选择教师"
                  clearable
                  filterable
              >
                <el-option
                    v-for="item in teacherOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.label"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="考试科目" prop="subject">
              <el-input v-model="examForm.subject" placeholder="请输入考试科目"/>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="考试时长" prop="timeLimit">
              <el-input-number
                  v-model="examForm.timeLimit"
                  :min="1"
                  :max="300"
                  style="width: 100%"
                  placeholder="考试时长">
                <template #append>分钟</template>
              </el-input-number>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker
                  style="width: 100%"
                  v-model="examForm.startTime"
                  type="datetime"
                  placeholder="选择考试开始时间"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="目标班级" prop="class">
              <el-select
                  v-model="examForm.class"
                  style="width: 100%"
                  placeholder="请选择班级"
                  clearable
                  filterable
              >
                <el-option
                    v-for="item in classOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="客观题占比" prop="objectiveScore">
              <el-input-number
                  v-model="examForm.objectiveScore"
                  :min="0"
                  :max="100"
                  style="width: 100%"
                  placeholder="客观题占比">
                <template #append>%</template>
              </el-input-number>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="主观题占比" prop="subjectiveScore">
              <el-input-number
                  v-model="examForm.subjectiveScore"
                  :min="0"
                  :max="100"
                  style="width: 100%"
                  placeholder="主观题占比">
                <template #append>%</template>
              </el-input-number>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="总分">
              <el-input disabled :value="examForm.totalScore" placeholder="自动计算">
                <template #append>分</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 客观题部分 -->
      <el-divider/>
      <el-row justify="space-between" align="middle">
        <el-col :span="4">
          <el-text type="primary">客观题</el-text>
        </el-col>
        <el-col :span="4" style="text-align: right;">
          <el-button icon="Plus" type="primary" plain @click="addObjectiveQuestion">新增客观题</el-button>
        </el-col>
      </el-row>
      <el-divider/>

      <div v-if="objectiveQuestions.length === 0" class="empty-tip">
        暂无客观题，请点击"新增客观题"按钮添加
      </div>

      <el-card v-for="(question, index) in objectiveQuestions" :key="question.id" class="question-card">
        <template #header>
          <div class="card-header">
            <span>客观题 {{ index + 1 }}</span>
            <el-button type="danger" size="small" @click="removeObjectiveQuestion(index)">删除</el-button>
          </div>
        </template>

        <el-form :model="question" label-width="100px">
          <el-form-item label="题目类型">
            <el-select v-model="question.type" placeholder="请选择题目类型" @change="handleQuestionTypeChange(question)">
              <el-option label="单选题" value="single"/>
              <el-option label="多选题" value="multiple"/>
              <el-option label="判断题" value="judge"/>
            </el-select>
          </el-form-item>

          <el-form-item label="题目内容">
            <el-input
                v-model="question.content"
                type="textarea"
                :rows="3"
                placeholder="请输入题目内容">
            </el-input>
          </el-form-item>

          <el-form-item label="分值">
            <el-input-number
                v-model="question.score"
                :min="0.5"
                :step="0.5"
                :precision="1"
                style="width: 200px">
            </el-input-number>
            <span style="margin-left: 10px;">分</span>
          </el-form-item>

          <el-form-item label="选项" v-if="question.type !== 'judge'">
            <div v-for="(option, optIndex) in question.options" :key="optIndex" class="option-item">
              <el-input
                  v-model="option.text"
                  placeholder="请输入选项内容"
                  style="width: 300px; margin-right: 10px;">
                <template #prepend>{{ String.fromCharCode(65 + optIndex) }}.</template>
              </el-input>
              <el-checkbox v-model="option.isCorrect">正确答案</el-checkbox>
              <el-button
                  type="danger"
                  size="small"
                  icon="Delete"
                  circle
                  @click="removeOption(question, optIndex)"
                  style="margin-left: 10px;">
              </el-button>
            </div>
            <el-button
                type="primary"
                plain
                icon="Plus"
                @click="addOption(question)"
                style="margin-top: 10px;">
              添加选项
            </el-button>
          </el-form-item>

          <el-form-item label="答案" v-if="question.type === 'judge'">
            <el-radio-group v-model="question.correctAnswer">
              <el-radio :label="true">正确</el-radio>
              <el-radio :label="false">错误</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 主观题部分 -->
      <el-divider/>
      <el-row justify="space-between" align="middle">
        <el-col :span="4">
          <el-text type="primary">主观题</el-text>
        </el-col>
        <el-col :span="4" style="text-align: right;">
          <el-button icon="Plus" type="primary" plain @click="addSubjectiveQuestion">新增主观题</el-button>
        </el-col>
      </el-row>
      <el-divider/>

      <div v-if="subjectiveQuestions.length === 0" class="empty-tip">
        暂无主观题，请点击"新增主观题"按钮添加
      </div>

      <el-card v-for="(question, index) in subjectiveQuestions" :key="question.id" class="question-card">
        <template #header>
          <div class="card-header">
            <span>主观题 {{ index + 1 }}</span>
            <el-button type="danger" size="small" @click="removeSubjectiveQuestion(index)">删除</el-button>
          </div>
        </template>

        <el-form :model="question" label-width="100px">
          <el-form-item label="题目内容">
            <el-input
                v-model="question.content"
                type="textarea"
                :rows="4"
                placeholder="请输入题目内容">
            </el-input>
          </el-form-item>

          <el-form-item label="分值">
            <el-input-number
                v-model="question.score"
                :min="1"
                :step="1"
                style="width: 200px">
            </el-input-number>
            <span style="margin-left: 10px;">分</span>
          </el-form-item>

          <el-form-item label="参考答案">
            <el-input
                v-model="question.referenceAnswer"
                type="textarea"
                :rows="4"
                placeholder="请输入参考答案">
            </el-input>
          </el-form-item>

          <el-form-item label="评分标准">
            <el-input
                v-model="question.scoringCriteria"
                type="textarea"
                :rows="3"
                placeholder="请输入评分标准">
            </el-input>
          </el-form-item>
        </el-form>
      </el-card>

    </el-scrollbar>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button icon="Check" type="primary" @click="submitExam">
          确认创建
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {computed, onMounted, reactive, ref, watch} from "vue";
import dayjs from 'dayjs';
import {allUserData} from "../../api/user/user.ts";
import {ElMessage, ElMessageBox, FormInstance, FormRules} from 'element-plus';
import 'dayjs/locale/zh-cn';
import {v4 as uuidv4} from 'uuid';
import {allClassData} from "../../api/class/class.ts";
import {createNewTes} from '../../api/tesPaper/tesPaper.ts'
import edit from './edit.vue'
import { useRouter } from 'vue-router';

const router = useRouter();

dayjs.locale('zh-cn');
// 对话框控制
const dialogVisible = ref(false);
const examFormRef = ref<FormInstance>();

// 当前时间计算
const currentTime = computed(() => dayjs().format('YYYY年MM月DD日 HH:mm:ss'));

// 考试表单数据
const examForm = reactive({
  id: uuidv4(),
  name: '',
  objectiveScore: 40,
  subjectiveScore: 60,
  totalScore: 100,
  teacherId: null as number | null,
  teacherName: '',
  subject: '',
  timeLimit: 120,
  startTime: '',
  class: '',
  state: 1,
  content: [],
});

// 表单验证规则
const formRules: FormRules = {
  name: [
    { required: true, message: '请输入考试名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  teacherName: [
    { required: true, message: '请选择教师', trigger: 'change' }
  ],
  subject: [
    { required: true, message: '请输入考试科目', trigger: 'blur' }
  ],
  timeLimit: [
    { required: true, message: '请输入考试时长', trigger: 'blur' },
    { type: 'number', min: 1, max: 300, message: '时长应在1-300分钟之间', trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: '请选择考试开始时间', trigger: 'change' }
  ],
  class: [
    { required: true, message: '请选择目标班级', trigger: 'change' }
  ],
  objectiveScore: [
    { required: true, message: '请输入客观题占比', trigger: 'blur' },
    { type: 'number', min: 0, max: 100, message: '占比应在0-100之间', trigger: 'blur' }
  ],
  subjectiveScore: [
    { required: true, message: '请输入主观题占比', trigger: 'blur' },
    { type: 'number', min: 0, max: 100, message: '占比应在0-100之间', trigger: 'blur' }
  ]
};

// 计算总分
watch(
    [() => examForm.objectiveScore, () => examForm.subjectiveScore],
    ([newObjective, newSubjective]) => {
      const objScore = Number(newObjective) || 0;
      const subScore = Number(newSubjective) || 0;
      examForm.totalScore = objScore + subScore;
    }
);

// 题目数据结构
interface ObjectiveQuestion {
  id: string;
  type: 'single' | 'multiple' | 'judge';
  content: string;
  score: number;
  options: {
    text: string;
    isCorrect: boolean;
  }[];
  correctAnswer?: boolean; // 判断题答案
}

interface SubjectiveQuestion {
  id: string;
  content: string;
  score: number;
  referenceAnswer: string;
  scoringCriteria: string;
}

// 题目列表
const objectiveQuestions = reactive<ObjectiveQuestion[]>([]);
const subjectiveQuestions = reactive<SubjectiveQuestion[]>([]);

// 选项数据
interface SelectOption {
  value: number;
  label: string;
}

const teacherOptions = ref<SelectOption[]>([]);
const classOptions = ref<SelectOption[]>([]);

// 获取用户数据
const fetchUserData = async () => {
  try {
    const SysUser = {router: "student"};
    const res = await allUserData(SysUser);
    teacherOptions.value = res.data.map(item => ({
      value: item.id ?? 0,
      label: item.name ?? '未知用户'
    }));
  } catch (err) {
    console.error("获取用户数据失败:", err);
    ElMessage.error('获取用户数据失败');
  }
};

// 获取班级数据
const fetchClassData = async () => {
  try {
    const res = await allClassData();
    classOptions.value = res.data.map(item => ({
      value: item.id,
      label: item.name
    }));
  } catch (err) {
    console.error("获取班级数据失败:", err);
    ElMessage.error('获取班级数据失败');
  }
};

// 监听教师选择
watch(() => examForm.teacherName, (newId) => {
  examForm.teacherId = newId ?? null;
});

// 打开对话框
const openDialog = () => {
  dialogVisible.value = true;
  resetForm();
};

// 重置表单
const resetForm = () => {
  Object.assign(examForm, {
    id: uuidv4(),
    name: '',
    teacherName: '',
    teacherId: null,
    subject: '',
    timeLimit: 120,
    startTime: '',
    class: '',
    objectiveScore: 40,
    subjectiveScore: 60,
    totalScore: 100,
  });

  objectiveQuestions.length = 0;
  subjectiveQuestions.length = 0;
};

// 客观题操作
const addObjectiveQuestion = () => {
  const newQuestion: ObjectiveQuestion = {
    id: uuidv4(),
    type: 'single',
    content: '',
    score: 5,
    options: [
      {text: '', isCorrect: false},
      {text: '', isCorrect: false},
      {text: '', isCorrect: false},
      {text: '', isCorrect: false}
    ]
  };
  objectiveQuestions.push(newQuestion);
};

const removeObjectiveQuestion = (index: number) => {
  ElMessageBox.confirm('确定要删除这道客观题吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    objectiveQuestions.splice(index, 1);
    ElMessage.success('删除成功');
  }).catch(() => {
  });
};

const handleQuestionTypeChange = (question: ObjectiveQuestion) => {
  if (question.type === 'judge') {
    question.options = [];
    question.correctAnswer = true;
  } else {
    question.correctAnswer = undefined;
    if (question.options.length === 0) {
      question.options = [
        {text: '', isCorrect: false},
        {text: '', isCorrect: false},
        {text: '', isCorrect: false},
        {text: '', isCorrect: false}
      ];
    }
  }
};

const addOption = (question: ObjectiveQuestion) => {
  if (question.options.length < 10) {
    question.options.push({text: '', isCorrect: false});
  } else {
    ElMessage.warning('最多只能添加10个选项');
  }
};

const removeOption = (question: ObjectiveQuestion, index: number) => {
  if (question.options.length > 2) {
    question.options.splice(index, 1);
  } else {
    ElMessage.warning('至少需要保留2个选项');
  }
};

// 主观题操作
const addSubjectiveQuestion = () => {
  const newQuestion: SubjectiveQuestion = {
    id: uuidv4(),
    content: '',
    score: 10,
    referenceAnswer: '',
    scoringCriteria: ''
  };
  subjectiveQuestions.push(newQuestion);
};

const removeSubjectiveQuestion = (index: number) => {
  ElMessageBox.confirm('确定要删除这道主观题吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    subjectiveQuestions.splice(index, 1);
    ElMessage.success('删除成功');
  }).catch(() => {
  });
};

// 提交考试
const submitExam = async () => {
  if (!examFormRef.value) return;

  try {
    await examFormRef.value.validate();

    // 验证题目
    if (objectiveQuestions.length === 0 && subjectiveQuestions.length === 0) {
      ElMessage.error('请至少添加一道题目');
      return;
    }

    // 验证客观题
    for (const question of objectiveQuestions) {
      if (!question.content) {
        ElMessage.error('请填写所有客观题的题目内容');
        return;
      }
      if (question.type !== 'judge') {
        const hasCorrectOption = question.options.some(opt => opt.isCorrect);
        if (!hasCorrectOption) {
          ElMessage.error('请为客观题设置正确答案');
          return;
        }
      }
    }

    // 验证主观题
    for (const question of subjectiveQuestions) {
      if (!question.content) {
        ElMessage.error('请填写所有主观题的题目内容');
        return;
      }
    }

    // 组装最终数据
    examForm.content.push(...objectiveQuestions);
    examForm.content.push(...subjectiveQuestions);

    console.log("准备创建的考试数据:", examForm);

    // TODO: 在这里调用 API 提交数据
    await createNewTes(examForm).then(res => {
      console.log("创建的考试数据:", res);
    }).catch(err => {
      console.error("创建考试数据失败:", err);
    });

    // 模拟提交成功
    ElMessage.success('考试安排创建成功！');
    dialogVisible.value = false;
    resetForm();
    router.go(0);
  } catch (error) {
    console.error('表单验证失败:', error);
  }
};

// 初始化
onMounted(() => {
  fetchUserData();
  fetchClassData();
});
</script>

<style scoped>
.el-col {
  margin-bottom: 15px;
}

.question-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.option-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.dialog-footer {
  text-align: right;
}

.empty-tip {
  text-align: center;
  padding: 20px;
  color: #999;
  background-color: #f5f7fa;
  border-radius: 4px;
}
</style>
